import cv2
import numpy as np
from PIL.Image import Image


def image_to_opencv(pil_image: Image) -> np.ndarray:
    """
    将PIL图像转换为OpenCV格式
    :param pil_image: PIL图像
    :return: OpenCV图像
    """
    # 将RGB转换为BGR，即将PIL图像转换为OpenCV格式
    return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)


def find_image_diff(img1: np.ndarray, img2: np.ndarray) -> list:
    """
    查找两张图片的差异区域
    :param img1: 第一张图片
    :param img2: 第二张图片
    :return: 差异区域列表
    """
    if img1.shape != img2.shape:
        raise ValueError("图像尺寸不一致")

    # 计算差异
    diff = cv2.absdiff(img1, img2)  # 计算像素差异
    # 转换为灰度图像
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    # 二值化
    _, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 提取差异区域
    regions = []
    for cnt in contours:
        # 过滤掉面积较小的轮廓，cv2.contourArea() 函数用于计算轮廓的面积
        if cv2.contourArea(cnt) > 100:
            x, y, w, h = cv2.boundingRect(cnt)  # 计算轮廓的外接矩形
            regions.append({"x": x, "y": y, "width": w, "height": h})
    return regions
